package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        UserDTO user = UserHolder.getUser();
        String key = "follow:" + user.getId();
        if (isFollow) {
                Follow follow = new Follow();
                follow.setUserId(user.getId());
                follow.setFollowUserId(followUserId);
                save(follow);
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
        } else {
            remove(new QueryWrapper<Follow>().eq("follow_user_id", followUserId).eq("user_id", user.getId()));
            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        UserDTO user = UserHolder.getUser();
        String key = "follow:" + user.getId();
        Boolean member = stringRedisTemplate.opsForSet().isMember(key, followUserId.toString());
        boolean isFollow = BooleanUtil.isTrue(member);
        return Result.ok(isFollow);
    }

    @Override
    public Result common(Long id) {
        String key1 = "follow:" + UserHolder.getUser().getId();
        String key2 = "follow:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (intersect != null) {
            List<Long> ids = intersect.stream().map(Long::valueOf).toList();
            List<UserDTO> userDTOS = userService.query().in("id", ids).last("order by field(id," + StrUtil.join(",", ids) + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
            return Result.ok(userDTOS);
        }
        return Result.ok(0);
    }
}
